Java Generics-এ Generic Methods ব্যবহার করে আমরা টাইপ-স্বাধীন কোড লিখতে পারি। একটি Generic Method সেই পদ্ধতিকে বোঝায় যেখানে একটি বা একাধিক টাইপ প্যারামিটার পদ্ধতির সংজ্ঞায় ব্যবহৃত হয়। এটি কোডের পুনর্ব্যবহারযোগ্যতা বাড়ায় এবং টাইপ সেফটি নিশ্চিত করে।
Generic Methods এর Syntax
modifier <T> returnType methodName(T parameter) {
// Method body
}
Syntax এর উপাদানসমূহ:
- Modifier: পদ্ধতির অ্যাক্সেস মডিফায়ার (যেমন
public,private, ইত্যাদি)। - Type Parameter:
<T>হল টাইপ প্যারামিটার। এটি কম্পাইল টাইমে নির্দিষ্ট টাইপ দ্বারা প্রতিস্থাপিত হয়। এটি পদ্ধতির নামের আগে ঘোষণা করা হয়।T,E,K,V, ইত্যাদি সাধারণত টাইপ প্যারামিটার হিসেবে ব্যবহৃত হয়।
- Return Type: পদ্ধতি যে টাইপের মান রিটার্ন করবে।
- Method Name: পদ্ধতির নাম।
- Parameter: পদ্ধতির ইনপুট প্যারামিটার, যা টাইপ প্যারামিটার ব্যবহার করতে পারে।
Generic Method এর উদাহরণ
1. একটি সাধারণ Generic Method:
public class GenericExample {
// Generic Method
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] strArray = {"Hello", "World"};
// Method call with Integer array
printArray(intArray);
// Method call with String array
printArray(strArray);
}
}
আউটপুট:
1
2
3
Hello
World
2. Multiple Type Parameters:
public class GenericExample {
// Generic Method with two type parameters
public static <T, U> void display(T first, U second) {
System.out.println("First: " + first);
System.out.println("Second: " + second);
}
public static void main(String[] args) {
display(10, "Generics");
display(3.14, true);
}
}
আউটপুট:
First: 10
Second: Generics
First: 3.14
Second: true
3. Bounded Type Parameters:
public class GenericExample {
// Generic Method with bounded type parameter
public static <T extends Number> void printDouble(T number) {
System.out.println("Double value: " + (number.doubleValue() * 2));
}
public static void main(String[] args) {
printDouble(5); // Integer
printDouble(3.14); // Double
}
}
আউটপুট:
Double value: 10.0
Double value: 6.28
4. Generic Method in a Generic Class:
public class GenericClass<T> {
private T data;
public GenericClass(T data) {
this.data = data;
}
// Generic Method
public <U> void print(U additionalData) {
System.out.println("Data: " + data);
System.out.println("Additional Data: " + additionalData);
}
public static void main(String[] args) {
GenericClass<String> example = new GenericClass<>("Hello");
example.print(123); // Generic Method call
}
}
আউটপুট:
Data: Hello
Additional Data: 123
Generic Methods-এর সুবিধা:
- Reusable Code: Generic Methods ব্যবহার করে একাধিক টাইপের জন্য একই পদ্ধতি ব্যবহার করা যায়।
- Type Safety: টাইপ সংক্রান্ত ত্রুটি কম্পাইল টাইমে ধরা যায়।
- Cleaner Code: টাইপ-ক্যাস্টিংয়ের প্রয়োজন হয় না, ফলে কোড আরও পড়তে সহজ হয়।
- Flexible: একাধিক টাইপ প্যারামিটার ব্যবহার করে আরও জটিল সমস্যার সমাধান করা যায়।
Content added By
Read more